<?php

namespace Common\Model;
use Think\Model;

class UserCarCodeModel extends Model {

	Const VALIDATE_TIME = 180;	//有效期，3分钟内

	Const STATUS_INIT = 0;		//初始化状态
	Const STATUS_USED = 1;		//已使用过

	protected $tableName = 'user_car_code';

	protected $_validate = array(
		['phone','/^1[34578]\d{9}$/','手机号不正确'],
   	);

   	protected $_auto = array (
   		['create_time','time',self::MODEL_INSERT,'function'],
   		['validate_time','getValidateTime',self::MODEL_INSERT,'callback'],
   		['status',self::STATUS_INIT]
    );

   	/**
   	 * 生成验证时间
   	 */
   	public function getValidateTime(){
   		return time()+self::VALIDATE_TIME;
   	}

   	/**
   	 * 生成验证码
   	 * @return [type] [description]
   	 */
    public function generateCode(){
    	return mt_rand(100000,999999);
    }

    /**
     * 校验验证码是否正确
     * @param  [type] $code [description]
     * @return [type]       [description]
     */
    public function varifyCode($code_id,$code,$phone){
    	$codeInfo = $this->where(['id'=>$code_id])->find();
    	if(!$codeInfo){
    		return '验证码不正确';
    	}
    	if($codeInfo['status']!=self::STATUS_INIT){
    		return '验证码已使用，请重新发送';
    	}
    	if(time()>$codeInfo['validate_time']){
    		return '验证码超时，请重新发送';
    	}
    	if($codeInfo['code'] != $code){
    		return '验证码不正确，请重试';
    	}
    	if($codeInfo['phone']!=$phone){
    		return '手机不正确，请重试';
    	}

    	$this->status = self::STATUS_USED;
    	$this->save();

    	return true;
    }

}